<?php

if (!$_FILES['gpsfile']['tmp_name']) {
?>
<html>
<head>
	<title>Upload a garmin gps file</title>
</head>
<body>
<form enctype="multipart/form-data" action="loadmytracks_uploader.php" method="POST">
	<input name="gpsfile" type="file" />
	<input type="submit" value="Send File" />
</form>
</body>
</html>
<?php
exit;
}

echo "<a href=\"loadmytracks_uploader.php\">Upload another</a>";

function message($msg) {
	echo "<li>" . $msg . "</li>";
}

function run_query($query) {
	$DB_USER="mxdb";
	$DB_PASS="tagger";
	$DB_HOST="localhost";
	$DB_NAME="mxdb";
	$dbh = mysql_connect($DB_HOST, $DB_USER, $DB_PASS);
	mysql_select_db($DB_NAME, $dbh);
	$result = mysql_query($query, $dbh);
	if (!$result)
		die('<result type="failure">Invalid query: ' . mysql_error() . '</result>');
	return $result;
}

function createTrack() {
	$query = "INSERT INTO mxdb.gps_track (id, tstamp) VALUES (NULL, NOW())";
	$result = run_query($query);
	$track_id = mysql_insert_id();
	return $track_id;
}

function createLap($track_id) {
	$query = "INSERT INTO mxdb.gps_lap (id, track_id, tstamp) VALUES (NULL, $track_id, NOW())";
	$result = run_query($query);
	return mysql_insert_id();
}

function createTrackpoint($lap_id, $tstamp, $lat, $lon, $ele, $distance) {
	if (!$distance) $distance = 0;
	$query = "INSERT INTO mxdb.gps_trackpoint (id, lap_id, tstamp, latitude, longitude, altitude, distance)" .
		" VALUES (NULL, " . $lap_id . ",'" . $tstamp . "'," . $lat . "," . $lon . "," . $ele . ", " . $distance . ")";
	$result = run_query($query);
	return mysql_insert_id();
}

function trackpointExists($track_time) {
	$track_time = preg_replace("/T/", " ", $track_time);
	$track_time = preg_replace("/Z/", "", $track_time);
	$query = "SELECT id FROM mxdb.gps_trackpoint WHERE tstamp = '" . $track_time . "'";
	$result = run_query($query);
	return mysql_num_rows($result) > 0;
}

message("copy(" . $_FILES['gpsfile']['tmp_name'] . ", uploads/" . $_FILES['gpsfile']['name']);
copy($_FILES['gpsfile']['tmp_name'], "/home/magex/Sites/mxgps/uploads/" . $_FILES['gpsfile']['name']); //"" . $_FILES['gpsfile']['name']);

message("Starting " . $_FILES['gpsfile']['name']);

$xmlstr = "";

$filename = $_FILES['gpsfile']['tmp_name'];
if (!($fp = fopen($filename, "r"))) { die("cannot open ".$filename); }
while ($data = fread($fp, 4096)) {
	$xmlstr .= $data;
}


$xmlstr = str_replace("<extensions>", "", $xmlstr);
$xmlstr = str_replace("</extensions>", "", $xmlstr);
$xmlstr = str_replace("gpxdata:", "", $xmlstr);

$xml = new SimpleXMLElement($xmlstr);


$namespaces = $xml->getNamespaces(true);

for ($i = 0; $i < count($xml->trk); $i++) {
	$trk = $xml->trk[$i];
	$track_time = $trk->trkseg[0]->trkpt[0]->time;
	if (true || !trackpointExists($track_time)) {
		$track_id = createTrack();
		message("Created Track: " . $track_id);
		for ($j = 0; $j < count($trk->trkseg); $j++) {
			$lap = $trk->trkseg[$j];
			$lap_id = createLap($track_id);
			message("Created Lap: " . $lap_id);
			for ($k = 0; $k < count($lap->trkpt); $k++) {
				$trkpt = $lap->trkpt[$k];
				createTrackpoint($lap_id, $trkpt->time, $trkpt['lat'], $trkpt['lon'], $trkpt->ele, $trkpt->distance);
			}
		}
	} else {
		message("Skipping track on: " . $track_time);
	}
}

$query = "SELECT lap_id, MIN(id) as minid, MAX(id) as maxid FROM gps_trackpoint WHERE lap_id not in (select id as lap_id from tagger_entity where type = 'garmin_lap') GROUP BY lap_id";
$result = run_query($query);
while ($row = mysql_fetch_row($result)) {
	$track_id = $row[0];
	$min_id = $row[1];
	$max_id = $row[2];

	run_query("INSERT INTO mxdb.tagger_entity (owner, title, type, tags, visibility) VALUES (1, 'New Garmin Lap', 'garmin_lap', 'inbox', 'private')");
	$entity_id = mysql_insert_id();
	message("Created tagger entity " . $entity_id);
	
	run_query("INSERT INTO mxdb.tagger_meta (id, k, v) VALUES ($track_id, 'garmin.lap_id', '$track_id')");
	run_query("INSERT INTO mxdb.tagger_meta (id, k, v) VALUES ($track_id, 'garmin.pointquery', '$min_id-$max_id')");
}

?>
